<template>
  <div class="event-list-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-title">
        <h2>比赛项目管理</h2>
        <p>管理系统中的所有比赛项目信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd" v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:add') || hasPermission('event')">
          <el-icon><Plus /></el-icon>
          新增项目
        </el-button>
        <el-button type="success" @click="handleImport" v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:import') || hasPermission('event')">
          <el-icon><Upload /></el-icon>
          导入项目
        </el-button>
        <el-button type="info" @click="handleExport" v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:export') || hasPermission('event')">
          <el-icon><Download /></el-icon>
          导出项目
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="请输入项目名称、编码或地点"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="项目类型">
          <el-select v-model="searchForm.eventType" placeholder="请选择项目类型" clearable style="width: 140px;">
            <el-option label="全部" :value="null"/>
            <el-option label="个人项目" :value="1"/>
            <el-option label="团体项目" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="性别限制">
          <el-select v-model="searchForm.genderLimit" placeholder="请选择性别限制" clearable style="width: 140px;">
            <el-option label="全部" :value="null"/>
            <el-option label="不限" :value="0"/>
            <el-option label="男子" :value="1"/>
            <el-option label="女子" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄分组">
          <el-select v-model="searchForm.ageGroup" placeholder="请选择年龄分组" clearable style="width: 140px;">
            <el-option label="全部" value=""/>
            <el-option label="儿童组" value="儿童组"/>
            <el-option label="少年组" value="少年组"/>
            <el-option label="青年组" value="青年组"/>
            <el-option label="中年组" value="中年组"/>
            <el-option label="老年组" value="老年组"/>
            <el-option label="不限年龄" value="不限年龄"/>
          </el-select>
        </el-form-item>
        <el-form-item label="成绩单位">
          <el-select v-model="searchForm.unit" placeholder="请选择成绩单位" clearable style="width: 120px;">
            <el-option label="全部" value=""/>
            <el-option label="秒" value="秒"/>
            <el-option label="分钟" value="分钟"/>
            <el-option label="米" value="米"/>
            <el-option label="厘米" value="厘米"/>
            <el-option label="分数" value="分数"/>
            <el-option label="次数" value="次数"/>
            <el-option label="公斤" value="公斤"/>
            <el-option label="名次" value="名次"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option label="全部" :value="null"/>
            <el-option label="禁用" :value="0"/>
            <el-option label="正常" :value="1"/>
            <el-option label="报名中" :value="2"/>
            <el-option label="比赛中" :value="3"/>
            <el-option label="已结束" :value="4"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button 
            type="danger" 
            :disabled="selectedEvents.length === 0" 
            @click="handleBatchDelete"
            v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:delete') || hasPermission('event')"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-button @click="loadEventList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table 
        :data="eventList" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="eventName" label="项目名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="eventCode" label="项目编码" width="120" show-overflow-tooltip />
        <el-table-column prop="eventType" label="项目类型" width="100">
          <template #default="{ row }">
            {{ getEventTypeText(row.eventType) }}
          </template>
        </el-table-column>
        <el-table-column prop="genderLimit" label="性别限制" width="100">
          <template #default="{ row }">
            {{ getGenderLimitText(row.genderLimit) }}
          </template>
        </el-table-column>
        <el-table-column prop="maxParticipants" label="最大参赛人数" width="120" />
        <el-table-column prop="scoringMethod" label="计分方式" width="100" />
        <el-table-column prop="venue" label="比赛地点" min-width="120" show-overflow-tooltip />
        <el-table-column prop="competitionTime" label="比赛时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.competitionTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="assignedJudges" label="分配裁判" width="150">
          <template #default="{ row }">
            <span v-if="row.assignedJudges && row.assignedJudges.length > 0">
              <el-tag 
                v-for="judge in row.assignedJudges.slice(0, 2)" 
                :key="judge.id" 
                size="small" 
                style="margin-right: 4px;"
              >
                {{ judge.realName }}
              </el-tag>
              <span v-if="row.assignedJudges.length > 2">
                +{{ row.assignedJudges.length - 2 }}
              </span>
            </span>
            <el-tag v-else type="warning" size="small">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:edit') || hasPermission('event')"
            />
            <el-tag v-else :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              size="small" 
              @click="handleEdit(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:edit') || hasPermission('event')"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              link 
              size="small" 
              @click="handleAssignJudge(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:edit') || hasPermission('event')"
            >
              分配裁判
            </el-button>
            <el-button 
              type="info" 
              link 
              size="small" 
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button 
              type="danger" 
              link 
              size="small" 
              @click="handleDelete(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:delete') || hasPermission('event')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 比赛项目表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :before-close="handleDialogClose"
      @opened="handleDialogOpened"
      v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:edit') || hasPermission('event')"
    >
      <el-form
        ref="eventFormRef"
        :model="eventForm"
        :rules="eventFormRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="eventName">
              <el-input v-model="eventForm.eventName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编码" prop="eventCode">
              <el-input v-model="eventForm.eventCode" placeholder="请输入项目编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目类型" prop="eventType">
              <el-select v-model="eventForm.eventType" placeholder="请选择项目类型" style="width: 100%;">
                <el-option label="个人项目" value="个人项目"/>
                <el-option label="团体项目" value="团体项目"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别分组" prop="genderGroup">
              <el-select v-model="eventForm.genderGroup" placeholder="请选择性别分组" style="width: 100%;">
                <el-option label="男子组" value="男子组"/>
                <el-option label="女子组" value="女子组"/>
                <el-option label="混合组" value="混合组"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄分组" prop="ageGroup">
              <el-select v-model="eventForm.ageGroup" placeholder="请选择年龄分组" style="width: 100%;">
                <el-option label="儿童组(6-12岁)" value="儿童组"/>
                <el-option label="少年组(13-17岁)" value="少年组"/>
                <el-option label="青年组(18-35岁)" value="青年组"/>
                <el-option label="中年组(36-50岁)" value="中年组"/>
                <el-option label="老年组(51岁以上)" value="老年组"/>
                <el-option label="不限年龄" value="不限年龄"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大参赛人数" prop="maxParticipants">
              <el-input-number v-model="eventForm.maxParticipants" :min="1" :max="1000" placeholder="请输入最大参赛人数" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计分方式" prop="scoreType">
              <el-select v-model="eventForm.scoreType" placeholder="请选择计分方式" style="width: 100%;">
                <el-option label="时间" value="时间"/>
                <el-option label="距离" value="距离"/>
                <el-option label="高度" value="高度"/>
                <el-option label="分数" value="分数"/>
                <el-option label="排名" value="排名"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成绩单位" prop="unit">
              <el-select v-model="eventForm.unit" placeholder="请选择成绩单位" style="width: 100%;">
                <el-option label="秒(s)" value="秒"/>
                <el-option label="分钟(min)" value="分钟"/>
                <el-option label="小时(h)" value="小时"/>
                <el-option label="米(m)" value="米"/>
                <el-option label="厘米(cm)" value="厘米"/>
                <el-option label="千米(km)" value="千米"/>
                <el-option label="分数(分)" value="分数"/>
                <el-option label="次数(次)" value="次数"/>
                <el-option label="个数(个)" value="个数"/>
                <el-option label="公斤(kg)" value="公斤"/>
                <el-option label="克(g)" value="克"/>
                <el-option label="环数(环)" value="环数"/>
                <el-option label="名次" value="名次"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="比赛日期" prop="eventDate">
              <el-date-picker
                v-model="eventForm.eventDate"
                type="date"
                placeholder="请选择比赛日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="比赛时间" prop="eventTime">
              <el-time-picker
                v-model="eventForm.eventTime"
                placeholder="请选择比赛时间"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="比赛地点" prop="venue">
              <el-input v-model="eventForm.venue" placeholder="请输入比赛地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="eventForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目描述" prop="description">
              <el-input 
                v-model="eventForm.description" 
                type="textarea"
                :rows="3"
                placeholder="请输入项目描述、规则说明等"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="eventForm.remark" 
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 裁判员分配对话框 -->
    <el-dialog
      v-model="judgeAssignDialogVisible"
      title="分配裁判员"
      width="800px"
      v-if="userStore.userInfo?.username === 'admin' || hasPermission('event:edit') || hasPermission('event')"
    >
      <div class="judge-assign-content">
        <div class="event-info">
          <h3>{{ selectedEvent.eventName }}</h3>
          <p>项目编码：{{ selectedEvent.eventCode }}</p>
          <p>比赛时间：{{ formatDateTime(selectedEvent.competitionTime) }}</p>
          <p>比赛地点：{{ selectedEvent.venue }}</p>
        </div>
        
        <el-divider>选择裁判员</el-divider>
        
        <div class="judge-selection">
          <div class="search-judge">
            <el-input
              v-model="judgeSearchKeyword"
              placeholder="搜索裁判员姓名或工号"
              @input="searchJudges"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="available-judges">
            <h4>可选裁判员</h4>
            <el-scrollbar height="200px">
              <div class="judge-list">
                <div 
                  v-for="judge in availableJudges" 
                  :key="judge.id"
                  class="judge-item"
                  @click="addJudgeToEvent(judge)"
                >
                  <div class="judge-info">
                    <span class="judge-name">{{ judge.realName }}</span>
                    <span class="judge-detail">{{ judge.workNumber }} | {{ judge.department }}</span>
                    <span class="judge-level">{{ judge.professionalLevel }}</span>
                  </div>
                  <el-button type="primary" size="small" plain>
                    <el-icon><Plus /></el-icon>
                  </el-button>
                </div>
              </div>
            </el-scrollbar>
          </div>
          
          <div class="assigned-judges">
            <h4>已分配裁判员</h4>
            <el-scrollbar height="200px">
              <div class="judge-list">
                <div 
                  v-for="judge in assignedJudges" 
                  :key="judge.id"
                  class="judge-item assigned"
                >
                  <div class="judge-info">
                    <span class="judge-name">{{ judge.realName }}</span>
                    <span class="judge-detail">{{ judge.workNumber }} | {{ judge.department }}</span>
                    <span class="judge-level">{{ judge.professionalLevel }}</span>
                  </div>
                  <el-button 
                    type="danger" 
                    size="small" 
                    plain
                    @click="removeJudgeFromEvent(judge)"
                  >
                    <el-icon><Minus /></el-icon>
                  </el-button>
                </div>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="judgeAssignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveJudgeAssignment" :loading="assignLoading">
            保存分配
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 比赛项目详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="比赛项目详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="项目名称">{{ eventDetail.eventName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目编码">{{ eventDetail.eventCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目类型">{{ getEventTypeText(eventDetail.eventType) }}</el-descriptions-item>
        <el-descriptions-item label="性别分组">{{ getGenderLimitText(eventDetail.genderLimit) }}</el-descriptions-item>
        <el-descriptions-item label="年龄分组">{{ eventDetail.ageGroup || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最大参赛人数">{{ eventDetail.maxParticipants || '-' }}</el-descriptions-item>
        <el-descriptions-item label="计分方式">{{ eventDetail.scoringMethod || '-' }}</el-descriptions-item>
        <el-descriptions-item label="成绩单位">{{ eventDetail.unit || '-' }}</el-descriptions-item>
        <el-descriptions-item label="比赛日期">{{ formatDate(eventDetail.competitionTime) }}</el-descriptions-item>
        <el-descriptions-item label="比赛时间">{{ formatTime(eventDetail.competitionTime) }}</el-descriptions-item>
        <el-descriptions-item label="比赛地点">{{ eventDetail.venue || '-' }}</el-descriptions-item>
        <el-descriptions-item label="比赛时长">{{ eventDetail.durationMinutes ? eventDetail.durationMinutes + '分钟' : '-' }}</el-descriptions-item>
        <el-descriptions-item label="报名开始时间">{{ formatDateTime(eventDetail.registrationStartTime) }}</el-descriptions-item>
        <el-descriptions-item label="报名结束时间">{{ formatDateTime(eventDetail.registrationEndTime) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(eventDetail.status)" size="small">
            {{ getStatusText(eventDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(eventDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="项目描述" :span="2">{{ eventDetail.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="比赛规则" :span="2">{{ eventDetail.rules || '-' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getEventList, createEvent, updateEvent, deleteEvent, 
  batchDeleteEvents, toggleEventStatus, getEventDetail,
  getEventJudges, assignJudgesToEvent
} from '@/api/event'
import { getJudgeList } from '@/api/judge'
import {
  Plus, Search, Refresh, Delete, Upload, Download, Minus
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 数据状态
const loading = ref(false)
const eventList = ref([])
const selectedEvents = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  eventType: null,
  genderLimit: null,
  ageGroup: '',
  unit: '',
  status: null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentEventId = ref(null)
const submitLoading = ref(false)
const eventFormRef = ref(null)

// 详情对话框
const detailDialogVisible = ref(false)
const eventDetail = ref({})

// 裁判员分配对话框
const judgeAssignDialogVisible = ref(false)
const selectedEvent = ref({})
const availableJudges = ref([])
const assignedJudges = ref([])
const judgeSearchKeyword = ref('')
const assignLoading = ref(false)

// 比赛项目表单
const eventForm = reactive({
  eventName: '',
  eventCode: '',
  eventType: '',
  genderGroup: '',
  ageGroup: '',
  maxParticipants: null,
  scoreType: '',
  unit: '',
  eventDate: '',
  eventTime: '',
  venue: '',
  description: '',
  remark: '',
  status: 1
})

// 表单验证规则
const eventFormRules = {
  eventName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '项目名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  eventCode: [
    { required: true, message: '请输入项目编码', trigger: 'blur' },
    { min: 2, max: 20, message: '项目编码长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  eventType: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  genderGroup: [
    { required: true, message: '请选择性别分组', trigger: 'change' }
  ],
  ageGroup: [
    { required: true, message: '请输入年龄分组', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大参赛人数', trigger: 'blur' }
  ],
  scoreType: [
    { required: true, message: '请选择计分方式', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入成绩单位', trigger: 'blur' }
  ],
  eventDate: [
    { required: true, message: '请选择比赛日期', trigger: 'change' }
  ],
  eventTime: [
    { required: true, message: '请选择比赛时间', trigger: 'change' }
  ],
  venue: [
    { required: true, message: '请输入比赛地点', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑比赛项目' : '新增比赛项目')

// 权限检查 - 取消权限认证，所有登录用户都可以访问
const hasPermission = (permission) => {
  return true
}

// 时间格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 日期格式化
const formatDate = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 时间格式化
const formatTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取项目类型文本
const getEventTypeText = (eventType) => {
  if (eventType === null || eventType === undefined) return '-'
  switch (eventType) {
    case 1: return '个人项目'
    case 2: return '团体项目'
    default: return '未知'
  }
}

// 获取性别限制文本
const getGenderLimitText = (genderLimit) => {
  if (genderLimit === null || genderLimit === undefined) return '-'
  switch (genderLimit) {
    case 0: return '不限'
    case 1: return '男子'
    case 2: return '女子'
    default: return '未知'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  if (status === null || status === undefined) return '-'
  switch (status) {
    case 0: return '禁用'
    case 1: return '正常'
    case 2: return '报名中'
    case 3: return '比赛中'
    case 4: return '已结束'
    default: return '未知'
  }
}

// 获取状态标签颜色
const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'danger'   // 禁用 - 红色
    case 1: return 'success'  // 正常 - 绿色
    case 2: return 'warning'  // 报名中 - 橙色
    case 3: return 'primary'  // 比赛中 - 蓝色
    case 4: return 'info'     // 已结束 - 灰色
    default: return ''
  }
}

// 加载比赛项目列表
const loadEventList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const response = await getEventList(params)
    eventList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载比赛项目列表失败:', error)
    ElMessage.error('加载比赛项目列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadEventList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    eventType: null,
    genderLimit: null,
    ageGroup: '',
    unit: '',
    status: null
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadEventList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadEventList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedEvents.value = selection
}

// 新增比赛项目
const handleAdd = () => {
  isEdit.value = false
  currentEventId.value = null
  resetEventForm()
  dialogVisible.value = true
}

// 编辑比赛项目
const handleEdit = (row) => {
  isEdit.value = true
  currentEventId.value = row.id
  
  // 映射后端字段到前端表单字段
  Object.assign(eventForm, {
    eventName: row.eventName || '',
    eventCode: row.eventCode || '',
    eventType: row.eventType === 1 ? '个人项目' : row.eventType === 2 ? '团体项目' : '',
    genderGroup: row.genderLimit === 0 ? '混合组' : row.genderLimit === 1 ? '男子组' : row.genderLimit === 2 ? '女子组' : '',
    ageGroup: row.ageGroup || '',
    maxParticipants: row.maxParticipants ? parseInt(row.maxParticipants) : null,
    scoreType: row.scoringMethod || '',
    unit: row.unit || '',
    eventDate: row.competitionTime ? row.competitionTime.split('T')[0] : '',
    eventTime: row.competitionTime ? row.competitionTime.split('T')[1]?.substring(0, 5) : '',
    venue: row.venue || '',
    description: row.description || '',
    remark: row.rules || '',
    status: row.status || 1
  })
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await getEventDetail(row.id)
    eventDetail.value = {
      ...response.data,
      maxParticipants: response.data.maxParticipants ? parseInt(response.data.maxParticipants) : null
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取比赛项目详情失败:', error)
    ElMessage.error('获取比赛项目详情失败')
  }
}

// 删除比赛项目
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除比赛项目"${row.eventName}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteEvent(row.id)
    ElMessage.success('删除成功')
    loadEventList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除比赛项目失败:', error)
      ElMessage.error('删除比赛项目失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedEvents.value.length} 个比赛项目吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedEvents.value.map(event => event.id)
    await batchDeleteEvents(ids)
    ElMessage.success('批量删除成功')
    loadEventList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    // 检查是否为管理员账号
    const isAdmin = userStore.userInfo?.username === 'admin'
    
    if (isAdmin || hasPermission('event:edit') || hasPermission('event')) {
      // 管理员或有权限的用户允许修改
      await toggleEventStatus(row.id, row.status)
      ElMessage.success(`比赛项目已${row.status === 1 ? '启用' : '禁用'}`)
    } else {
      // 无权限用户不允许修改
      throw new Error('您没有修改比赛项目状态的权限')
    }
  } catch (error) {
    console.error('更新比赛项目状态失败:', error)
    ElMessage.error(error.message || '更新比赛项目状态失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 导入比赛项目
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 导出比赛项目
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 分配裁判员
const handleAssignJudge = async (row) => {
  selectedEvent.value = row
  judgeAssignDialogVisible.value = true
  
  // 从后端加载已分配的裁判员
  try {
    const response = await getEventJudges(row.id)
    assignedJudges.value = response.data || []
  } catch (error) {
    console.error('加载已分配裁判员失败:', error)
    assignedJudges.value = []
  }
  
  await loadAvailableJudges()
}

// 加载可用裁判员列表
const loadAvailableJudges = async () => {
  try {
    const response = await getJudgeList({
      current: 1,
      size: 100, // 获取更多裁判员
      status: 1   // 只获取正常状态的裁判员
    })
    
    // 过滤掉已分配的裁判员
    const assignedJudgeIds = assignedJudges.value.map(judge => judge.id)
    availableJudges.value = response.data.records.filter(
      judge => !assignedJudgeIds.includes(judge.id)
    )
  } catch (error) {
    console.error('加载裁判员列表失败:', error)
    ElMessage.error('加载裁判员列表失败')
  }
}

// 搜索裁判员
const searchJudges = async () => {
  try {
    const response = await getJudgeList({
      current: 1,
      size: 100,
      realName: judgeSearchKeyword.value,
      status: 1
    })
    
    const assignedJudgeIds = assignedJudges.value.map(judge => judge.id)
    availableJudges.value = response.data.records.filter(
      judge => !assignedJudgeIds.includes(judge.id)
    )
  } catch (error) {
    console.error('搜索裁判员失败:', error)
  }
}

// 添加裁判员到项目
const addJudgeToEvent = (judge) => {
  assignedJudges.value.push(judge)
  availableJudges.value = availableJudges.value.filter(j => j.id !== judge.id)
}

// 从项目中移除裁判员
const removeJudgeFromEvent = (judge) => {
  assignedJudges.value = assignedJudges.value.filter(j => j.id !== judge.id)
  availableJudges.value.push(judge)
}

// 保存裁判员分配
const saveJudgeAssignment = async () => {
  try {
    assignLoading.value = true
    
    // 获取当前分配的裁判员ID列表
    const judgeIds = assignedJudges.value.map(j => j.id)
    
    // 调用API保存分配关系
    await assignJudgesToEvent(selectedEvent.value.id, judgeIds)
    
    ElMessage.success('裁判员分配成功')
    judgeAssignDialogVisible.value = false
    // 刷新项目列表以显示更新的分配信息
    await loadEventList()
  } catch (error) {
    console.error('保存裁判员分配失败:', error)
    ElMessage.error('保存裁判员分配失败')
  } finally {
    assignLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!eventFormRef.value) return
  
  try {
    await eventFormRef.value.validate()
    submitLoading.value = true
    
    // 映射前端表单字段到后端字段
    const formData = {
      eventName: eventForm.eventName,
      eventCode: eventForm.eventCode || eventForm.eventName, // 如果没有编码，使用名称
      eventType: eventForm.eventType === '个人项目' ? 1 : eventForm.eventType === '团体项目' ? 2 : 1,
      genderLimit: eventForm.genderGroup === '男子组' ? 1 : eventForm.genderGroup === '女子组' ? 2 : 0,
      ageGroup: eventForm.ageGroup,
      maxParticipants: eventForm.maxParticipants,
      description: eventForm.description,
      rules: eventForm.remark,
      scoringMethod: eventForm.scoreType,
      unit: eventForm.unit,
      venue: eventForm.venue,
      competitionTime: (() => {
        if (eventForm.eventDate && eventForm.eventTime) {
          // 处理时间格式，确保是字符串
          const timeStr = typeof eventForm.eventTime === 'string' ? 
            eventForm.eventTime : 
            eventForm.eventTime.toTimeString().substring(0, 5)
          return `${eventForm.eventDate}T${timeStr}:00`
        }
        return eventForm.eventDate ? `${eventForm.eventDate}T00:00:00` : null
      })(),
      status: eventForm.status
    }
    
    // 检查是否为管理员账号
    const isAdmin = userStore.userInfo?.username === 'admin'
    
    if (isEdit.value) {
      if (isAdmin || hasPermission('event:edit') || hasPermission('event')) {
        await updateEvent(currentEventId.value, formData)
        ElMessage.success('更新成功')
      } else {
        throw new Error('您没有编辑比赛项目的权限')
      }
    } else {
      if (isAdmin || hasPermission('event:add') || hasPermission('event')) {
        await createEvent(formData)
        ElMessage.success('创建成功')
      } else {
        throw new Error('您没有创建比赛项目的权限')
      }
    }
    
    dialogVisible.value = false
    loadEventList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 对话框打开后的处理
const handleDialogOpened = () => {
  // 对话框完全打开后，如果是新增模式，确保表单为空
  if (!isEdit.value) {
    setTimeout(() => {
      resetEventForm()
    }, 100)
  }
}

// 关闭对话框
const handleDialogClose = (done) => {
  dialogVisible.value = false
  resetEventForm()
  if (typeof done === 'function') {
    done()
  }
}

// 重置表单
const resetEventForm = () => {
  // 先清空表单验证
  if (eventFormRef.value) {
    eventFormRef.value.resetFields()
    eventFormRef.value.clearValidate()
  }
  
  // 重置表单数据
  Object.assign(eventForm, {
    eventName: '',
    eventCode: '',
    eventType: '',
    genderGroup: '',
    ageGroup: '',
    maxParticipants: null,
    scoreType: '',
    unit: '',
    eventDate: '',
    eventTime: '',
    venue: '',
    description: '',
    remark: '',
    status: 1
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadEventList()
})
</script>

<style scoped>
.event-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title h2 {
  color: #303133;
  margin: 0 0 8px 0;
  font-size: 24px;
}

.header-title p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: -18px;
}

.search-form .el-select {
  min-width: 120px;
}

.table-card {
  margin-bottom: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 裁判员分配对话框样式 */
.judge-assign-content .event-info {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.judge-assign-content .event-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.judge-assign-content .event-info p {
  margin: 4px 0;
  color: #606266;
  font-size: 14px;
}

.judge-assign-content .judge-selection {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.judge-assign-content .search-judge {
  grid-column: 1 / -1;
  margin-bottom: 16px;
}

.judge-assign-content .available-judges h4,
.judge-assign-content .assigned-judges h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.judge-assign-content .judge-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.judge-assign-content .judge-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.judge-assign-content .judge-item.assigned {
  background-color: #f0f9ff;
  border-color: #409eff;
}

.judge-assign-content .judge-info {
  flex: 1;
}

.judge-assign-content .judge-name {
  display: block;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.judge-assign-content .judge-detail {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.judge-assign-content .judge-level {
  display: inline-block;
  background: #e1f3d8;
  color: #529b2e;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .table-toolbar {
    flex-direction: column;
    gap: 12px;
  }
  
  .judge-assign-content .judge-selection {
    grid-template-columns: 1fr !important;
  }
}
</style>
